class Person < ActiveRecord::Base
  attr_accessible :name, :national_id, :give
  has_many :bags
  validates_uniqueness_of :national_id
  before_create :set_receive_date
  def self.search(search)
    search_condition = "%" + search + "%"
    find(:all, :conditions => ['name LIKE ? OR national_id LIKE ?', search_condition, search_condition])
  end
  
  def give_bag
    bags = Bag.all
    bags.each do |bag|
      if bag.person.nil?
        self.bags << bag
        self.save!
        self.give=false
        self.save!
        break
      end
    end
  end
  
  def self.user_by_receive_date date
    search_condition = "" + date 
    find(:all, :conditions => ['receive_date LIKE ? ', search_condition])
  end
  
  def set_receive_date
    count = Person.all.count
    if count == 0 
      date = 1
    else
      date = ((count-1)/50)+1
    end
    final_date = date.to_s
    self.receive_date = final_date
  end
end
